package org.practice;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

/**
 * @author zch
 */
public class AlternatePrint {

    public static void main(String[] args) throws InterruptedException {
        String nums = "1234567";
        String alphabets = "abcdefg";
        alternatePrint0(nums.toCharArray(), alphabets.toCharArray());
        TimeUnit.SECONDS.sleep(1);
        alternatePrint1(nums.toCharArray(), alphabets.toCharArray());
    }

    private static final Object LOCK = new Object();
    private static void alternatePrint0(char[] nums, char[] alphabets) {
        Thread thread1 = createThreadInstance(nums, "thread--1");;
        Thread thread2 = createThreadInstance(alphabets, "thread--2");
        thread1.start();
        thread2.start();
    }

    private static Thread t1 = null, t2 = null;
    private static void alternatePrint1(char[] nums, char[] alphabets) {
        t1 = new Thread(() -> {
            for (char num : nums) {
                System.out.print(num);
                LockSupport.unpark(t2);
                LockSupport.park();
            }
        }, "thread--1");

        t2 = new Thread(() -> {
            for (char aChar : alphabets) {
                LockSupport.park();
                System.out.print(aChar);
                LockSupport.unpark(t1);
            }
        }, "thread--1");
        t1.start();
        t2.start();
    }

    private static Thread createThreadInstance(char[] items, String threadName) {
        return new Thread(() -> {
            for (char item : items) {
                synchronized (LOCK) {
                    System.out.print(item);
                    LOCK.notify();
                    try {
                        LOCK.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, threadName);
    }

}
